package org.apak.frontend;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apak.db.RepairServiceDAO;
import org.apak.model.LoggedSubject;
import org.apak.model.ServiceNote;
import org.apak.model.ServiceOrder;

@SuppressWarnings("serial")
public class SaveNoteServlet extends HttpServlet {

	private RepairServiceDAO dao = new RepairServiceDAO();
	private HttpSession session;

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		if (session.getAttribute("loggedSubject") == null) {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("error.jsp");
			dispatcher.forward(request, response);
		} else {
			LoggedSubject loggedSubject = (LoggedSubject) session
					.getAttribute("loggedSubject");
			ServiceOrder currentServiceOrder = (ServiceOrder) session
					.getAttribute("currentServiceOrder");
			if(!loggedSubject.isCustomer()) {
				ServiceNote serviceNote = dao.getEmployeeServiceNote(
						loggedSubject.getSubject_id(),
						currentServiceOrder.getService_order());
				if (serviceNote == null) {
					String result = dao.addEmployeeServiceNote(
							loggedSubject.getSubject_id(),
							currentServiceOrder.getService_order(),
							request.getParameter("note"));
					response.getWriter().println(result);
				} else {
					String result = dao.updateEmployeeServiceNote(request.getParameter("note"),
							loggedSubject.getSubject_id(),
							currentServiceOrder.getService_order());
					response.getWriter().println(result);
				}
			} else {
				ServiceNote serviceNote = dao.getCustomerServiceNote(Integer.parseInt(request.getParameter("service_order_fk")));
				if (serviceNote == null) {
					String result = dao.addCustomerServiceNote(
							loggedSubject.getSubject_id(),
							Integer.parseInt(request.getParameter("service_order_fk")),
							request.getParameter("note"));
					response.getWriter().println(result);
				} else {
					String result = dao.updateCustomerServiceNote(request.getParameter("note"),
							loggedSubject.getSubject_id(),
							Integer.parseInt(request.getParameter("service_order_fk")));
					response.getWriter().println(result);
				}
			}
			
			
		}
	}
}
